import axios from '@/utils/request'
const ORDER_STATUS = {
  '-2': '支付失败',
  '-1': '已取消',
  1: '待支付',
  2: '已支付',
  3: '已发货',
  4: '已完成',
  5: '已完成'
}

export default {
  Order: {
    form: {
      fields: [
        // 'store',
        // {
        //   property: 'status',
        //   type: 'select',
        //   type_options: {
        //     options: [
        //       { value: '-2', label: '支付失败' },
        //       { value: '-1', label: '已取消' },
        //       { value: '1', label: '待支付' },
        //       { value: '2', label: '已支付' },
        //       { value: '3', label: '已发货' },
        //       { value: '4', label: '已收货' },
        //       { value: '5', label: '已完成' }
        //     ]
        //   }
        // }
        { property: 'comment', type: 'input' }
      ]
    },
    list: {
      // export: {
      //   query: {
      //     '@display': `{
      //       'id' : 'entity.getId()',
      //       'no' : 'entity.getNo()',
      //       'createdTime' : 'entity.getCreatedTime().format("Y-m-d H:i:s")',
      //       'store' : 'entity.getStore().__toString()',
      //       'name': 'entity.getName()',
      //       'spu': 'entity.getSpu()',
      //       'phone': 'entity.getPhone()',
      //       'address': 'entity.getAddress()',
      //       'items' : 'ArrayCommon.reduce(entity.getItems().toArray(), "carry~item.__toString()~hyphen", null, { hyphen : "; "} )',
      //       'status' : '${JSON.stringify(ORDER_STATUS)}[entity.getStatus()]',
      //       'totalPrice' : 'entity.getTotalPrice()',
      //       'discount' : 'entity.getDiscount()',
      //       'price' : 'entity.getPrice()',
      //       'comment': 'entity.getComment()'
      //     }`,
      //     limit: 10000000
      //   },
      //   label: {
      //     'id': 'id',
      //     'no': '订单号',
      //     'createdTime': '创建时间',
      //     'store': '店铺',
      //     'name': '客户',
      //     'phone': '电话',
      //     'spu': '产品编码',
      //     'address': '地址',
      //     'items': '产品',
      //     'status': '状态',
      //     'totalPrice': '总价',
      //     'discount': '优惠',
      //     'price': '实收',
      //     'comment': '备注'
      //   }
      // },
      disabled_actions: ['new', 'edit', 'delete', 'lines'],
      query: {
        '@filter': `entity.getStatus() != 0`,
        '@order': 'entity.id|DESC',
        '@expands': "['entity.items.specification.product']",
        limit: 10
      },
      list_filter: {
        'order.store.id': () => {
          return axios
            .get(`/manage/stores`)
            .then(res =>
              Object.assign({ __label: '下单门店' },
                ...res.data.map(v => { return { [v.id]: v.name } })))
        },
        'order.shippingStore.id': () => {
          return axios
            .get(`/manage/stores`)
            .then(res =>
              Object.assign({ __label: '发货门店' },
                ...res.data.map(v => { return { [v.id]: v.name } })))
        },
        // 'specification.id': () => {
        //   return axios
        //     .get(`/manage/specifications`, { params: { limit: 10000 } })
        //     .then(res =>
        //       Object.assign({ __label: '产品' },
        //         ...res.data.map(v => { return { [v.id]: v.name } })))
        // },
        beforeCreatedTime: {
          expression: 'entity.getCreatedTime() >= datetime.get(":value")',
          label: '下单开始时间',
          type: 'datetime'
        },
        afterCreatedTime: {
          expression: 'entity.getCreatedTime() < datetime.get(":value")',
          label: '下单结束时间',
          type: 'datetime'
        },
        status: Object.assign({ __label: '状态' }, ORDER_STATUS),
        phone: '电话',
        no: '订单号'
      },
      list_display: [
        {
          property: 'button',
          label: '操作',
          component: {
            props: ['record', 'refresh'],
            data() {
              return {
                loading: false,
                shippingData: [],
                show: false
              }
            },
            render(h) {
              if (parseInt(this.record.status) === 2) {
                return (
                  <div>
                    {/* <el-popconfirm title='确定发货当前订单？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.put(`/manage/orders/${this.record.id}`, { status: 3 }).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).finally(() => {
                              this.loading = false
                            })
                          }
                        }
                      }} style={{ marginLeft: '3px' }}>
                      <el-button slot='reference' size='small' type='primary' icon='el-icon-truck' loading={this.loading} plain>发货</el-button>
                    </el-popconfirm> */}
                    <el-popconfirm title='确定退款当前订单？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.post(`/manage/orders/${this.record.id}/cancel-and-refund`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).finally(() => {
                              this.loading = false
                            })
                          }
                        }
                      }} style={{ marginLeft: '3px' }}>
                      <el-button type='danger' slot='reference' size='small' icon='el-icon-refresh-left' loading={this.loading} plain>退款</el-button>
                    </el-popconfirm>
                  </div>
                )
              } else if (parseInt(this.record.status) === 1) {
                return (
                  <el-popconfirm title='确定取消当前订单？'
                    {...{
                      on: {
                        onConfirm: (val) => {
                          this.loading = true
                          axios.post(`/manage/orders/${this.record.id}/cancel-and-refund`).then((res) => {
                            this.$message.success('执行成功！')
                            this.refresh()
                          }).finally(() => {
                            this.loading = false
                          })
                        }
                      }
                    }} style={{ marginLeft: '3px' }}>
                    <el-button slot='reference' size='small' icon='el-icon-delete' loading={this.loading} plain>取消</el-button>
                  </el-popconfirm>
                )
              } else if (parseInt(this.record.status) >= 3) {
                return (
                  <div>
                    <el-dialog
                      title='物流信息'
                      visible={this.show}
                      onClose={() => { this.show = false }}
                      width='30%;'>
                      <div style='max-height: 80vh;overfloat:auto'>
                        <el-steps direction='vertical' active='1' finish-status='success'>
                          {this.shippingData.map(v => {
                            return <el-step title={v.msg} description={v.time}></el-step>
                          })}
                        </el-steps>
                      </div>
                    </el-dialog>
                    <el-button slot='reference' size='small' icon='el-icon-truck' loading={this.loading} onClick={() => {
                      this.loading = true
                      this.axios.get(`/public/orders/${this.record.id}/track-shipping`).then((res) => {
                        // console.log('shippingData', res.data)
                        const shippingData = []
                        for (let i of res.data.path_item_list) {
                          let date = new Date(i.action_time * 1000)
                          date = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
                          shippingData.push({
                            msg: i.action_msg,
                            time: date
                          })
                        }
                        this.shippingData = shippingData
                        this.show = true
                        this.loading = false
                      })
                    }} plain>查看物流</el-button>
                    <el-popconfirm title='确定退款当前订单？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.post(`/manage/orders/${this.record.id}/cancel-and-refund`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).finally(() => {
                              this.loading = false
                            })
                          }
                        }
                      }} style={{ marginLeft: '3px' }}>
                      <el-button type='danger' slot='reference' size='small' icon='el-icon-refresh-left' loading={this.loading} plain>退款</el-button>
                    </el-popconfirm>
                  </div>
                )
              }
            }
          }
        },
        // 'createdTime',
        // 'store',
        // 'name',
        // 'phone',
        // 'address',
        {
          property: 'store',
          label: '门店信息',
          component: {
            props: ['record'],
            render(h) {
              return <div style='font-size:12px'>
                <p>下单门店:{this.record.store.__toString}</p>
                <p>发货门店:{this.record.shippingStore ? this.record.shippingStore.__toString : this.record.store.__toString}</p>
              </div>
            }
          }
        },
        {
          property: 'shippingData',
          label: '订单信息',
          component: {
            props: ['record'],
            data() {
              return {
                createdTime: ''
              }
            },
            created() {
              const date = new Date(this.record.createdTime)
              this.createdTime = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
            },
            render(h) {
              if (this.record.shippingType == 'pickUp') {
                return <div style='font-size:12px'>
                  <p>下单时间：{this.createdTime}</p>
                  <p>订单编号: {this.record.no}</p>
                  <p>客户自提</p>
                </div>
              } else {
                return <div style='font-size:12px'>
                  <p>下单时间：{this.createdTime}</p>
                  <p>订单编号: {this.record.no}</p>
                  <p>{this.record.address}</p>
                  <p>
                    {this.record.name}({this.record.phone})
                  </p>
                </div>
              }

            }
          }
        },
        {
          property: 'items',
          label: '产品信息',
          component: {
            props: ['data'],
            render(h) {
              // console.log(this.data)
              return <div style='font-size:12px'>
                {
                  this.data.map(v => {
                    return <div>{v.__metadata.specification.__metadata.product.__toString}[{v.__metadata.specification.__metadata.name}]X{v.__metadata.quantity}</div>
                  })
                }
              </div>
            }
          }
        },
        {
          property: 'status',
          label: '订单状态',
          component: {
            props: ['data'],
            render(h) {
              return <div style='font-size:12px'>{ORDER_STATUS[this.data]}</div>
            }
          }
        },
        {
          property: 'paidData',
          label: '支付信息',
          component: {
            props: ['record'],
            render(h) {
              return <div style='font-size:12px'>
                <p>订单总价:￥{this.record.totalPrice}</p>
                <p>折让:￥{this.record.discount}</p>
                <p>积分抵扣:￥{this.record.paidPoint}</p>
                <p>实收:￥{this.record.price}</p>
              </div>
            }
          }
        },
        {
          property: 'recommendUser',
          label: '推荐用户'
        },
        {
          property: 'comment',
          label: '订单备注',
          component: {
            props: ['record'],
            render(h) {
              return <div style='font-size:12px'>
                {this.record.comment}
              </div>
            }
          }
        },
        {
          property: 'afterSales',
          label: '售后',
          component: {
            props: ['record'],
            data() {
              return {
                show: false
              }
            },
            render(h) {
              if (this.record.afterSalesStatus > 0) {
                return <div>
                  <div>
                    <el-dialog
                      title='售后流程'
                      visible={this.show}
                      width='50%'
                      onClose={() => { this.show = false }}
                    >
                      <div style='margin-bottom:50px'>
                        <el-steps direction='vertical' active={this.record.afterSalesStatus}>
                          {this.record.afterSales.map(v => {
                            return <el-step title={v.title} description={v.time + ' ' + v.comment} />
                          })}
                        </el-steps>
                      </div>
                    </el-dialog>
                    <div>
                      <el-button type='text' onClick={() => { this.show = true }}>查看售后</el-button>
                    </div>
                  </div >
                </div >
              } else {
                return <div>暂无售后</div>
              }
            }
          }
        }
        // {
        //   property: 'status',
        //   label: '订单状态',
        //   component: {
        //     props: ['data'],
        //     render(h) {
        //       return <div>{ORDER_STATUS[this.data]}</div>
        //     }
        //   }
        // },
      ]
    }
  }
}
